//
//  CEHomeViewController.m
//  C8 Energy
//
//  Created by 颜魏 on 2024/10/1.
//

#import "CEHomeViewController.h"
#import "CECategoryCollectionViewCell.h"
#import "CEVoltageCollectionViewCell.h"
#import "CETempCollectionViewCell.h"
#import <sqlite3.h>
#import "SPlayManager.h"
#import "PGDatePickManager.h"
#import "CustomCircleView.h"
#import "ProtectionTableViewCell.h"

@interface CEHomeViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, PGDatePickerDelegate, UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIView *circleView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *socLabel;

@property (weak, nonatomic) IBOutlet UILabel *socTotalLabel;
@property (weak, nonatomic) IBOutlet UILabel *socTotalTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *socBalanceLabel;
@property (weak, nonatomic) IBOutlet UILabel *socBalanceTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *cycleLabel;
@property (weak, nonatomic) IBOutlet UILabel *cycleTitleLabel;

@property (strong, nonatomic) IBOutletCollection(UIView) NSArray *mosViews;
@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *mosLabels;
@property (weak, nonatomic) IBOutlet UIButton *chgSW;
@property (weak, nonatomic) IBOutlet UIButton *balanceSW;
@property (weak, nonatomic) IBOutlet UIButton *disChgSW;
@property (weak, nonatomic) IBOutlet UIButton *heatSW;

@property (weak, nonatomic) IBOutlet UICollectionView *typeCollect;

@property (weak, nonatomic) IBOutlet UIView *warnView;
@property (weak, nonatomic) IBOutlet UIView *errorView;

@property (weak, nonatomic) IBOutlet UILabel *mouthLabel;
@property (weak, nonatomic) IBOutlet UILabel *voltageTitleLable;
@property (weak, nonatomic) IBOutlet UILabel *currentTitleLabel;
@property (weak, nonatomic) IBOutlet LineChartView *chartsView;

@property (weak, nonatomic) IBOutlet UILabel *singleVoltageTitleLabel;
@property (weak, nonatomic) IBOutlet UICollectionView *voltageCollect;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *voltageCollectH; //45

@property (weak, nonatomic) IBOutlet UICollectionView *tempCollect;
@property (weak, nonatomic) IBOutlet UILabel *singleTempTitleLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tempCollectH;  //40

@property (weak, nonatomic) IBOutlet UIView *protectionView;
@property (weak, nonatomic) IBOutlet UILabel *protectionTitleLabel;
@property (weak, nonatomic) IBOutlet UIButton *protectionCleanBtn;
@property (weak, nonatomic) IBOutlet UITableView *protectionTab;
@property (weak, nonatomic) IBOutlet UILabel *level1Label;
@property (weak, nonatomic) IBOutlet UILabel *level2Label;
@property (weak, nonatomic) IBOutlet UILabel *level3Label;

@property (weak, nonatomic) IBOutlet UIView *btStatusView;
@property (weak, nonatomic) IBOutlet UILabel *btStatusLabel;

@property (nonatomic, strong) CustomCircleView *cusCircleView;

@property (nonatomic, assign) CGFloat    soc;       //电池剩余电量
@property (nonatomic, assign) CGFloat    current;   //电流
@property (nonatomic, assign) CGFloat    voltage;   //电压
@property (nonatomic, assign) CGFloat    capacity;  //剩余电容
@property (nonatomic, assign) CGFloat    fullCapicity;  //满电电容
@property (nonatomic, assign) NSInteger  cycles;        //循环次数

@property (nonatomic, assign) NSInteger cbcCHG; //CBC_CHG异常标志
@property (nonatomic, assign) NSInteger cbcDSG; //CBC_DSG异常标志

@property (nonatomic, assign) NSInteger disChargingCurrent; //放电电流
@property (nonatomic, assign) NSInteger chargingCurrent; //充电电流

@property (nonatomic, assign) NSInteger voltageSingleExceed;            //单节过压
@property (nonatomic, assign) NSInteger voltageSingleLower;             //单节欠压
@property (nonatomic, assign) NSInteger voltageTotalLower;              //总压欠压
@property (nonatomic, assign) NSInteger chargingExceed;                 //充电过流
@property (nonatomic, assign) NSInteger disChargingExceed;              //放电过流
@property (nonatomic, assign) NSInteger chargingTemperatureExceed;      //充电过温
@property (nonatomic, assign) NSInteger disChargingTemperatureExceed;   //放电过温
@property (nonatomic, assign) NSInteger chargingTemperatureLower;       //充电低温
@property (nonatomic, assign) NSInteger disChargingTemperatureLower;    //放电低温
@property (nonatomic, assign) NSInteger voltageDifferenceExceed;        //压差过大
@property (nonatomic, assign) NSInteger res;        //预留
@property (nonatomic, assign) NSInteger socLow;        //soc过低
@property (nonatomic, assign) NSInteger mosOver;        //mos过温

@property (nonatomic, assign) NSInteger preMOS;     //预充MOS管
@property (nonatomic, assign) NSInteger chgMOS;     //充电MOS管
@property (nonatomic, assign) NSInteger dsgMOS;     //放电MOS管
@property (nonatomic, assign) NSInteger preRelay;   //预充继电器
@property (nonatomic, assign) NSInteger chgRelay;   //分口充电继电器
@property (nonatomic, assign) NSInteger dsgRelay;   //分口放电继电器
@property (nonatomic, assign) NSInteger mainRelay;  //同口主继电器
@property (nonatomic, assign) NSInteger heatingRelay;  //加热MOS
@property (nonatomic, assign) NSInteger heatingTemp;  //加热MOS温度

@property (nonatomic, assign) NSInteger balanceMode;
@property (nonatomic, assign) NSInteger heatMode;

@property (nonatomic, assign) NSInteger     logCount;   //写入日志间隔
@property (nonatomic, strong) NSMutableArray    *finalserialVoltageValue;   //单体电压
@property (nonatomic, strong) NSMutableArray    *temperatureSensor;   //触点温度1-6 3.2 主控读取电池温度电流等信息
@property (nonatomic, strong) NSMutableArray    *temperatureSensorAll;   //所有温度信息
@property (nonatomic, strong) NSMutableArray *historyDataArray; //历史图标数据
@property (nonatomic, strong) NSString *searchDate; //图标月份

@property (nonatomic, strong) NSTimer *queryTimer; //数据定时器
@property (nonatomic, strong) NSTimer *chartsTimer; //图标定时器
@property (nonatomic, assign) NSInteger     queryCount;   //查询次数
@property (nonatomic, assign) NSInteger     historyDataInsertCount;   //插入图标数据次数
@property (nonatomic, assign) BOOL isChgCurrent;    //是否是充电
@property (nonatomic, assign) BOOL  isCurrentPage;

@property (nonatomic, strong) NSMutableArray *protectionArray;
@property (nonatomic, strong) NSMutableArray *protectValue;
@property (nonatomic, assign) BOOL isUpgrading;

@end

@implementation CEHomeViewController
{
    sqlite3 *db;
    float environmentTemperature1, environmenTemperature2, environmenTemperature3, mosT;  //环境温度1，环境温度2，环境温度3
    float environmentHighTemperature; //环境最高温度
    float environmenLowTemperature; //环境最低温度
    int differentialPressure; //压差
    int vCellMax;//单节最高电压
    int cVellmin;//单节最低电压
    int averageVoltage; //平均电压
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.chartsTimer invalidate];
    self.chartsTimer = nil;
    [self.queryTimer invalidate];
    self.queryTimer = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.queryCount = 0;
    self.historyDataInsertCount = 0;
    self.isChgCurrent = YES;
    self.isCurrentPage = YES;
    self.isUpgrading = NO;
    self.historyDataArray = [[NSMutableArray alloc] init];
    self.finalserialVoltageValue = [[NSMutableArray alloc] init];
    self.temperatureSensor = [[NSMutableArray alloc] init];
    self.temperatureSensorAll = [[NSMutableArray alloc] init];
    self.protectionArray = [[NSMutableArray alloc] init];
    self.protectValue = [[NSMutableArray alloc] init];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_0", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_1", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_2", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_3", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_4", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_5", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_6", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_7", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_8", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_9", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_10", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_11", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_12", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_13", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_14", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_15", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_16", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_17", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_18", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_19", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_20", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_21", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_22", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_23", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_24", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_25", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_26", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_27", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_28", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_29", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_30", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_31", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_32", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_33", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_34", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_35", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_36", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_37", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_38", nil)];
    [self.protectValue addObject:NSLocalizedString(@"protectInfo_39", nil)];
    self.level1Label.text = NSLocalizedString(@"firstProtection", nil);
    self.level2Label.text = NSLocalizedString(@"secondProtection", nil);
    self.level3Label.text = NSLocalizedString(@"thirdProtection", nil);

    self.chargingCurrent = 0;
    self.disChargingCurrent = 0;

    [self.typeCollect registerNib:[UINib nibWithNibName:@"CECategoryCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"CECategoryCollectionViewCell"];
    [self.voltageCollect registerNib:[UINib nibWithNibName:@"CEVoltageCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"CEVoltageCollectionViewCell"];
    [self.tempCollect registerNib:[UINib nibWithNibName:@"CETempCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"CETempCollectionViewCell"];
    [self.protectionTab registerNib:[UINib nibWithNibName:@"ProtectionTableViewCell" bundle:nil] forCellReuseIdentifier:@"ProtectionTableViewCell"];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getLogData) name:@"GET_LOG_DATA" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logDelete) name:@"LOG_DATA_DELETE" object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectFail) name:kBTDisconnect object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectSuccess) name:kBTConnectionSucceed object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectDeviceName:) name:kBTConnectDeviceName object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReciveData:) name:kBTDidReciveData object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changePageShowState:) name:@"ChangePageShowState" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(upgradeUpdate:) name:kBTUpgrading object:nil];
    
    [self setLanguage];
    
    [self initSql];
    [self queryData];
    [self getChartData];
        
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *confromTimesp = [NSDate date];
    NSString *actiondate = [formatter stringFromDate:confromTimesp];
    self.mouthLabel.text = actiondate;
    
    self.cusCircleView = [[CustomCircleView alloc] initWithFrame:CGRectMake(0 , 0, 136, 136)];
    [self.circleView addSubview:self.cusCircleView];
}

- (void)connectFail {
    self.btStatusView.hidden = NO;
}

- (void)connectSuccess {
    self.btStatusView.hidden = YES;
}

- (void)upgradeUpdate:(NSNotification *)nf {
    self.isUpgrading = [nf.object integerValue] == 1;
}

- (void)setLanguage {
    self.titleLabel.text = NSLocalizedString(@"Work interface", nil);
    self.btStatusLabel.text = NSLocalizedString(@"Bluetooth disconnected, reconnecting...", nil);
    
    self.socTotalTitleLabel.text = [NSString stringWithFormat:@"%@ (Ah)", NSLocalizedString(@"Total Capacity", nil)];
    self.socBalanceTitleLabel.text = [NSString stringWithFormat:@"%@ (Ah)", NSLocalizedString(@"Remaining capacity", nil)];
    self.cycleTitleLabel.text = NSLocalizedString(@"Cycle", nil);
    
    self.protectionTitleLabel.text = NSLocalizedString(@"Protection Record", nil);
    [self.protectionCleanBtn setTitle:NSLocalizedString(@"Clear", nil) forState:UIControlStateNormal];
    
    UILabel *balanceLabel = self.mosLabels[0];
    balanceLabel.text = NSLocalizedString(@"Charge MOS", nil);
    UILabel *dischargeLabel = self.mosLabels[1];
    dischargeLabel.text = NSLocalizedString(@"Discharge MOS", nil);
    UILabel *chargeLabel = self.mosLabels[2];
    chargeLabel.text = NSLocalizedString(@"Balanced MOS", nil);
    UILabel *headLabel = self.mosLabels[3];
    headLabel.text = NSLocalizedString(@"Heating MOS", nil);
    
    self.currentTitleLabel.text = NSLocalizedString(@"Current", nil);
    self.voltageTitleLable.text = NSLocalizedString(@"Voltage", nil);
    
    self.singleVoltageTitleLabel.text = NSLocalizedString(@"Single cell voltage", nil);
    self.singleTempTitleLabel.text = NSLocalizedString(@"Temperature information", nil);

    for (UIView *view in self.mosViews) {
        [view layoutIfNeeded];
        view.layer.borderWidth = 1;
        view.layer.borderColor = RGB16(0xf5f6f7).CGColor;
        view.layer.masksToBounds = YES;
        view.layer.cornerRadius = 4;
    }
    
    [self.warnView layoutIfNeeded];
    self.warnView.layer.borderColor = RGB16(0xFE8C05).CGColor;
    self.warnView.layer.borderWidth = 1;
    self.warnView.layer.masksToBounds = YES;
    self.warnView.layer.cornerRadius = 10;
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = self.warnView.bounds;
    gradientLayer.colors = @[(id)RGB16(0xFFFBF6).CGColor, (id)[UIColor whiteColor].CGColor];
    gradientLayer.startPoint = CGPointMake(0.0, 0.0);
    gradientLayer.endPoint = CGPointMake(1.0, 1.0);
    [self.warnView.layer insertSublayer:gradientLayer atIndex:0];

    [self.errorView layoutIfNeeded];
    self.errorView.layer.borderColor = RGB16(0xFE4949).CGColor;
    self.errorView.layer.borderWidth = 1;
    self.errorView.layer.masksToBounds = YES;
    self.errorView.layer.cornerRadius = 10;
    CAGradientLayer *gradientLayer1 = [CAGradientLayer layer];
    gradientLayer1.frame = self.errorView.bounds;
    gradientLayer1.colors = @[(id)RGB16(0xFFF3F3).CGColor, (id)[UIColor whiteColor].CGColor];
    gradientLayer1.startPoint = CGPointMake(0.0, 0.0);
    gradientLayer1.endPoint = CGPointMake(1.0, 1.0);
    [self.errorView.layer insertSublayer:gradientLayer1 atIndex:0];

    [self.protectionView layoutIfNeeded];
    self.protectionView.layer.borderColor = RGB16(0xFE8C05).CGColor;
    self.protectionView.layer.borderWidth = 1;
    self.protectionView.layer.masksToBounds = YES;
    self.protectionView.layer.cornerRadius = 10;
    CAGradientLayer *gradientLayer2 = [CAGradientLayer layer];
    gradientLayer2.frame = self.protectionView.bounds;
    gradientLayer2.colors = @[(id)RGB16(0xFFFBF6).CGColor, (id)[UIColor whiteColor].CGColor];
    gradientLayer2.startPoint = CGPointMake(0.0, 0.0);
    gradientLayer2.endPoint = CGPointMake(1.0, 1.0);
    [self.protectionView.layer insertSublayer:gradientLayer2 atIndex:0];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.isCurrentPage = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.isCurrentPage = NO;
}

- (void)changePageShowState:(NSNotification *)nf {
    NSInteger state = [nf.object integerValue];
    self.isCurrentPage = state;
}

- (void)getChartData {
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *confromTimesp = [NSDate date];
    self.searchDate = [formatter stringFromDate:confromTimesp];
    WeakSelf
    self.chartsTimer = [NSTimer scheduledTimerWithTimeInterval:5 repeats:YES block:^(NSTimer * _Nonnull timer) {
        [weakSelf getChartsHistoryData];
    }];
    [self getChartsHistoryData];
}

- (void)queryData {
    WeakSelf
    self.queryTimer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
//        return;
        if (self.isUpgrading) return;
        if (!weakSelf.isCurrentPage) {
            return;
        }
        switch (weakSelf.queryCount) {
            case 0:
            {
                [weakSelf queryBMS];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf queryBatteryVersion];
                });
            }
                break;
            case 1:
                [weakSelf queryBatteryTemperature];
                break;
            case 2:
                [weakSelf queryBatteryOther];
                break;
            case 3:
                [weakSelf queryClock];
                break;
            default:
                break;
        }
        
        weakSelf.queryCount ++;
        if (weakSelf.queryCount > 3) {
            weakSelf.queryCount = 0;
        }
       
        weakSelf.historyDataInsertCount ++;
        if (weakSelf.historyDataInsertCount >= 5) {
            weakSelf.historyDataInsertCount = 0;
            NSString *historyVolate = [NSString stringWithFormat:@"%f", weakSelf.voltage];
            NSString *historyCurrent = [NSString stringWithFormat:@"%f", weakSelf.current];
            NSDictionary *dataDict = [NSDictionary dictionaryWithObjectsAndKeys:historyVolate,@"voltage",historyCurrent,@"current", nil];
            [weakSelf insertHistoryData:dataDict];
        }
    }];
}

- (void)displayChart {
    NSMutableArray *voltageArray = [NSMutableArray array];
    NSMutableArray *currentArray = [NSMutableArray array];
    NSMutableArray *dateArray = [NSMutableArray array];
    [self.chartsView setDragEnabled:true];
    [self.chartsView setScaleEnabled:false];
    //_chartView.setTouchEnabled(true);
    //_chartView.setHorizontalScrollBarEnabled(true);
    [self.chartsView setHighlightPerTapEnabled:false];
    [self.chartsView setHighlightPerDragEnabled:false];
    //_chartView.setHighlightPerTapEnabled(false);
    //_chartView.setHighlightPerDragEnabled(false);

    for (int i = 0; i < self.historyDataArray.count; i++) {
        NSString *recordVoltage,*recordCurrent;
        NSDictionary *aDicitonary = self.historyDataArray[i];
        recordVoltage=aDicitonary[@"voltage"];
        recordCurrent=aDicitonary[@"current"];
        float voltageValue=recordVoltage.floatValue;
        float currentValue=recordCurrent.floatValue;
        voltageValue = voltageValue/30.0;
        currentValue = currentValue/60.0;

        ChartDataEntry *entry,*currentEntry;
        entry=[[ChartDataEntry alloc] initWithX:i+1 y:voltageValue];
        currentEntry=[[ChartDataEntry alloc] initWithX:i+1 y:currentValue];
        [voltageArray addObject:entry];
        [currentArray addObject:currentEntry];
        NSString *dateString;
        dateString=aDicitonary[@"date"];
        dateString=[dateString substringWithRange:NSMakeRange(10, 9)];
        [dateArray addObject:dateString];
    }
    
    ChartXAxis *xAxis = self.chartsView.xAxis;
    xAxis.gridLineDashLengths = @[@3.0f, @3.0f];//设置虚线样式的网格线
    xAxis.gridColor = [UIColor colorWithRed:200/255.0f green:200/255.0f blue:200/255.0f alpha:1];//网格线颜色
    xAxis.gridAntialiasEnabled = YES;
    [xAxis setLabelTextColor:RGB16(0xA4A4A4)];
    [xAxis setLabelPosition:XAxisLabelPositionBottom];
    [xAxis setLabelCount:5];
    [xAxis setAxisMaximum:self.historyDataArray.count];
    [xAxis setAxisMinimum:0];
    [xAxis setAxisLineWidth:1.0f];
    [xAxis setAxisLineColor:RGB16(0xA4A4A4)];

    ChartYAxis *leftYAxis = self.chartsView.leftAxis;
    leftYAxis.gridLineDashLengths = @[@3.0f, @3.0f];//设置虚线样式的网格线
    leftYAxis.gridColor = [UIColor colorWithRed:200/255.0f green:200/255.0f blue:200/255.0f alpha:1];//网格线颜色
    leftYAxis.gridAntialiasEnabled = YES;
    [leftYAxis setLabelTextColor:RGB16(0xA4A4A4)];
    [leftYAxis setAxisMaximum:5];
    [leftYAxis setAxisMinimum:0];
    [leftYAxis setLabelCount:5];
    [leftYAxis setAxisLineColor:RGB16(0xA4A4A4)];
    
    ChartYAxis *rightYAxis = self.chartsView.rightAxis;
    rightYAxis.gridLineDashLengths = @[@3.0f, @3.0f];//设置虚线样式的网格线
    rightYAxis.gridColor = [UIColor clearColor];//网格线颜色
    rightYAxis.gridAntialiasEnabled = YES;
    [rightYAxis setLabelTextColor:RGB16(0xA4A4A4)];
    [rightYAxis setAxisMaximum:5];
    [rightYAxis setAxisMinimum:0];
    [rightYAxis setLabelCount:5];
    [rightYAxis setAxisLineColor:RGB16(0xA4A4A4)];
    //set
    LineChartDataSet *voltageSet = [[LineChartDataSet alloc] initWithEntries:voltageArray label:@""];
    [voltageSet setColor:RGB16(0x725CFA)];
    [voltageSet setCircleRadius:2.0f];
    [voltageSet setDrawValuesEnabled:YES];
    [voltageSet setValueTextColor:RGB16(0x725CFA)];
    voltageSet.valueFormatter = [VoltageValueFormatter new];
    LineChartDataSet *currentSet = [[LineChartDataSet alloc] initWithEntries:currentArray label:@""];
    [currentSet setColor:RGB16(0xEF7BE3)];
    [currentSet setCircleRadius:2.0f];
    [currentSet setDrawValuesEnabled:YES];
    [currentSet setValueTextColor:RGB16(0xEF7BE3)];
    currentSet.valueFormatter = [CurrentValueFormatter new];

//    [currentSet setBarBorderColor:[UIColor whiteColor]];
//    [currentSet setBarBorderWidth:0.5f];
    
    //显示图值并格式化
    ChartIndexAxisValueFormatter *xFormatter =  [[ChartIndexAxisValueFormatter alloc] initWithValues:dateArray];
    [xAxis setValueFormatter:xFormatter];
    
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    numberFormatter.positiveSuffix = @"V";
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    [numberFormatter setPositiveFormat:@"#0.0V"];
    ChartIndexAxisValueFormatter *formatter =  [[ChartIndexAxisValueFormatter alloc] initWithValues:[NSArray arrayWithObjects:@"0V",@"30V",@"60V",@"90V",@"120V",@"150V", nil]];
    [leftYAxis setValueFormatter:formatter];
    
    NSNumberFormatter *numberFormatterCurrent = [[NSNumberFormatter alloc] init];
    numberFormatterCurrent.positiveSuffix = @"A";
    [numberFormatterCurrent setNumberStyle:NSNumberFormatterDecimalStyle];
    [numberFormatterCurrent setPositiveFormat:@"#0.0A"];
    ChartIndexAxisValueFormatter *formatterCurrent = [[ChartIndexAxisValueFormatter alloc] initWithValues:[NSArray arrayWithObjects:@"0A", @"60A",@"120A",@"180A",@"240A",@"300A", nil]];
   
    [rightYAxis setValueFormatter:formatterCurrent];
    
    voltageSet.highlightEnabled = NO;
    LineChartData *data = [[LineChartData alloc] initWithDataSets:[NSArray arrayWithObjects:voltageSet,currentSet, nil]];
    self.chartsView.data = data;
    [self.chartsView setVisibleXRangeMaximum:5];
    [self.chartsView moveViewToX:self.historyDataArray.count];
}

#pragma mark - action
- (IBAction)actionBack:(id)sender {
    [[BTManager sharedBTManager] disconnectPeripheral:[BTManager sharedBTManager].peripheral];
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)actionMos:(UIButton *)sender {
//    NSInteger index = [self.mosBtns indexOfObject:sender];
    // 0.heat 1.balance 2.charge 3.discharge
}

- (IBAction)actionChangeMouth:(id)sender {
    PGDatePickManager *datePickManager = [[PGDatePickManager alloc]init];
    PGDatePicker *datePicker = datePickManager.datePicker;
    datePicker.datePickerMode = PGDatePickerModeDate;
    datePicker.delegate = self;
    [self presentViewController:datePickManager animated:false completion:nil];
}
- (IBAction)actionProtectionClean:(id)sender {
    Byte byte[] = {0x01,0x06,0x10,0x01,0x00,0x01,0x1d,0x0a};
    [[BTManager sharedBTManager] sendCommand:byte length:8];
    [self.protectionArray removeAllObjects];
    [self.protectionTab reloadData];
}

- (void)updateUI {
    self.cycleLabel.text = @(self.cycles).description;
    self.socLabel.text = @(self.soc).description;
    
    self.cusCircleView.rate = (NSInteger)self.soc;
    [self.cusCircleView startAnimation];

    self.socTotalLabel.text = [NSString stringWithFormat:@"%.1f", self.fullCapicity];
    self.socBalanceLabel.text = [NSString stringWithFormat:@"%.1f", self.capacity];

    self.heatSW.selected = self.heatMode == 1;
    self.balanceSW.selected = self.balanceMode == 1;
    self.chgSW.selected = (self.chgMOS == 1 || self.chgRelay == 1);
    self.disChgSW.selected = (self.dsgMOS == 1 || self.dsgRelay == 1 || self.mainRelay ==1);

    self.voltageCollectH.constant = 46 * ((self.finalserialVoltageValue.count/9 + (self.finalserialVoltageValue.count%9 ? 1 : 0)));
    
    NSInteger count = 0;
    for (NSInteger i=0; i<self.temperatureSensor.count; i++) {
        NSString *value = self.temperatureSensor[i];
        if (![value isEqualToString:@"-40"] || i == self.temperatureSensor.count-1) {
            count ++ ;
        }
    }
    self.tempCollectH.constant = 40 * ((count/5 + (count%5 ? 1 : 0)));
    
    [self.typeCollect reloadData];
    [self.voltageCollect reloadData];
    [self.tempCollect reloadData];
    [self.protectionTab reloadData];
}

#pragma mark - notification
- (void)connectDeviceName:(NSNotification *)nf {
    NSString *name = nf.object;
    self.nameLabel.text = name.length == 0 ? self.nameLabel.text : name;
}

- (void)didReciveData:(NSNotification *)notification {
    if (self.isUpgrading) return;
    NSData *reciveData = notification.object;
    Byte *dataBytes = (Byte*)reciveData.bytes;
//    NSLog(@"receieve %@", reciveData);
    if (dataBytes[2]==0x2a & reciveData.length>(3 + 0x03 * 2 + 11)) {
        //3.3 主控读取时钟及保护记录等信息
        //AFE1异常标志
        NSInteger afe1 = dataBytes[3+0x09*2];
        //AFE2异常标志
        NSInteger afe2 = dataBytes[3+0x09*2+1];
        //EEP通讯异常标志
        NSInteger can = dataBytes[3+0x0a*2];
        //EEP通讯异常标志
        NSInteger eepCommunicate = dataBytes[3+0x0a*2+1];
        NSInteger spi = dataBytes[3 + 0x0b * 2];
        NSInteger upper = dataBytes[3 + 0x0b * 2 + 1];
        NSInteger client1 = dataBytes[3 + 0x0c * 2];
        NSInteger lcd = dataBytes[3 + 0x0c * 2+1];
        NSInteger wifi = dataBytes[3 + 0x0d * 2];
        //EEP存储异常标志
        NSInteger eepStorage = dataBytes[3+0x0f*2];
        NSInteger hse = dataBytes[3 + 0x0f * 2 + 1];
        NSInteger lse = dataBytes[3 + 0x10 * 2];
        NSInteger flash = dataBytes[3 + 0x10 * 2 + 1];
        NSInteger balance = dataBytes[3 + 0x11 * 2];
        NSInteger adc = dataBytes[3 + 0x11 * 2 + 1];

        //CBC_CHG异常标志
        self.cbcCHG = dataBytes[3+0x0e*2+1];
        //CBC_DSG异常标志
        self.cbcDSG = dataBytes[3+0x13*2];
        if ((self.preMOS>0) | (self.chgMOS>0) | (self.dsgMOS>0) | (self.preRelay>0)| (self.chgRelay>0) | (self.dsgRelay>0) | (self.mainRelay>0)) {
            self.cbcDSG = 0;
            self.cbcDSG = 0;
        }
        NSInteger hardwareAlarm = afe1 + afe2 + can + eepCommunicate + spi + upper + client1 + lcd + wifi + eepStorage + hse + lse + flash + balance + adc + self.cbcDSG + self.cbcCHG;
        NSInteger batteryAlarm = self.voltageSingleExceed + self.voltageSingleLower + self.voltageTotalLower + self.chargingExceed + self.disChargingExceed + self.disChargingTemperatureExceed + self.disChargingTemperatureLower + self.voltageDifferenceExceed;
        if(hardwareAlarm + batteryAlarm > 0) {
            [[SPlayManager sharedManager] playAudio];
//            self.jhSW.on = NO;
        }else {
            [[SPlayManager sharedManager] stopAudio];
//            self.jhSW.on = YES;
        }
        
        [self.protectionArray removeAllObjects];
        [self.protectionArray addObject:[NSString stringWithFormat:@"%i",dataBytes[3 + 0x03 * 2 + 0]]];
        [self.protectionArray addObject:[NSString stringWithFormat:@"%i",dataBytes[3 + 0x03 * 2 + 4]]];
        [self.protectionArray addObject:[NSString stringWithFormat:@"%i",dataBytes[3 + 0x03 * 2 + 8]]];
        
        [self.protectionArray addObject:[NSString stringWithFormat:@"%i",dataBytes[3 + 0x03 * 2 + 1]]];
        [self.protectionArray addObject:[NSString stringWithFormat:@"%i",dataBytes[3 + 0x03 * 2 + 5]]];
        [self.protectionArray addObject:[NSString stringWithFormat:@"%i",dataBytes[3 + 0x03 * 2 + 9]]];
        
        [self.protectionArray addObject:[NSString stringWithFormat:@"%i",dataBytes[3 + 0x03 * 2 + 2]]];
        [self.protectionArray addObject:[NSString stringWithFormat:@"%i",dataBytes[3 + 0x03 * 2 + 6]]];
        [self.protectionArray addObject:[NSString stringWithFormat:@"%i",dataBytes[3 + 0x03 * 2 + 10]]];
        
        [self.protectionArray addObject:[NSString stringWithFormat:@"%i",dataBytes[3 + 0x03 * 2 + 3]]];
        [self.protectionArray addObject:[NSString stringWithFormat:@"%i",dataBytes[3 + 0x03 * 2 + 7]]];
        [self.protectionArray addObject:[NSString stringWithFormat:@"%i",dataBytes[3 + 0x03 * 2 + 11]]];

    }
    if ((dataBytes[2]==0x4c) & (reciveData.length>(3 + 35 * 2 + 1))) {
        //3.1 主控读取电池电压数据
        self.voltage = (float)(dataBytes[3+0x25*2]*256+dataBytes[3+0x25*2+1]);
        self.voltage = self.voltage / 100;

        differentialPressure = dataBytes[3+0x24*2]*256+dataBytes[3+0x24*2+1]; //压差
        vCellMax = dataBytes[3+0x20*2]*256+dataBytes[3+0x20*2+1];//单节最高电压
        cVellmin = dataBytes[3+0x21*2]*256+dataBytes[3+0x21*2+1];//单节最低电压
        averageVoltage = (vCellMax + cVellmin) / 2;
        
        [self.finalserialVoltageValue removeAllObjects];
        for (int t=0;t<32;t++) {
            int voltage = dataBytes[3+t*2]*256+dataBytes[3+t*2+1];
            if (voltage<60000 && voltage >= 1000) {
//                averageVoltage = averageVoltage+voltage;
                [self.finalserialVoltageValue addObject:[@(voltage/1000.0) description]];
            }
        }
//        averageVoltage = averageVoltage/self.finalserialVoltageValue.count;

        self.logCount ++;
        NSString *log = [[NSUserDefaults standardUserDefaults] objectForKey:LogInterval];
        if (!log) log = @"5";
        log = (log && log.length) ? log : @"5";
        if(self.logCount * 6 >= log.integerValue) {
            NSString *logStatus = [[NSUserDefaults standardUserDefaults] objectForKey:LogIsOpen];
            if ([logStatus isEqualToString:@"on"]) {
                self.logCount = 0;
                NSString *logDetail = @"";
                NSString *logName = @"";
                for (int t = 0; t < self.finalserialVoltageValue.count; t++) {
                    logDetail = [NSString stringWithFormat:@"%@ cell %i : %@ V",logDetail, t+1, self.finalserialVoltageValue[t]];
                }
                logDetail = [NSString stringWithFormat:@"%@ CBC_chg:%li BC_dsg:%li %@",[self getCurrentTimes], (long)self.cbcCHG / 10, (long)self.cbcDSG / 10, logDetail];
                logDetail = [NSString stringWithFormat:@"%@ %@ %.2fV %@:%liA %@:%liA", logDetail, @"Total Voltage", self.voltage, @"CCHG", (long)self.chargingCurrent / 10, @"CDSG", (long)self.disChargingCurrent / 10];
                logDetail = [NSString stringWithFormat:@"%@ SOC:%.1f％ %@  %f Ah ", logDetail, self.soc, @"Residual_capacity", self.capacity];
                logDetail = [NSString stringWithFormat:@"%@ :%@:%li %@:%li %@:%li ",logDetail, @"prefill MOS", (long)self.preMOS,
                             @"charge MOS", (long)self.chgMOS,
                             @"discharge MOS", (long)self.dsgMOS
                           ];
                logDetail = [NSString stringWithFormat:@"%@ ,%@:", logDetail, @"TTC"];
                for (int t = 0; t < self.temperatureSensorAll.count; t++) {
                    NSString *temp = [self.temperatureSensorAll[t] isEqualToString:@"-40"] ? @"NA" : self.temperatureSensorAll[t];
                    logDetail = [NSString stringWithFormat:@"%@%@℃, ", logDetail, temp];
                }
                logDetail = [NSString stringWithFormat:@"%@ %@:%li %@:%li %@:%li %@:%li %@:%li %@:%li %@:%li %@:%li %@:%li %@:%li %@:%li %@:%li %@:%li %@:%li\n",logDetail,
                             @"OV_Cell", (long)self.voltageSingleExceed,
                             @"UV_Cell", self.voltageSingleLower,
                             @"OV_Bat", self.voltageTotalLower,
                             @"UV_Bat", self.voltageTotalLower,
                             @"OC_CHG", self.chargingExceed,
                             @"OC_DSG", self.disChargingExceed,
                             @"OT_CHG", self.chargingTemperatureExceed,
                             @"UT_CHG",self.chargingTemperatureLower,
                             @"OT_DSG", self.disChargingTemperatureExceed,
                             @"UT_DSG", self.disChargingTemperatureLower,
                             @"Voltage difference is too large", self.voltageDifferenceExceed,
                             @"Prepare", self.res,
                             @"OT_MOS", self.mosOver,
                             @"Low SOC", self.socLow
                           ];
                [self insertData:logName logDetail:logDetail];
            }
        }
    }

    if ((dataBytes[2]==0x32) & (reciveData.length>30)) {
        //3.2 主控读取电池温度电流等信息
        //循环次数
        self.cycles = dataBytes[3+0x13*2]*256 + dataBytes[3+0x13*2+1];
        int serialBalance16 = dataBytes[3+0x17*2]*256+dataBytes[3+0x17*2+1]; //1-16 均衡状态
        int serialBalance32 = dataBytes[3+0x18*2]*256+dataBytes[3+0x18*2+1]; //17-32 均衡状态
        self.balanceMode = (serialBalance16>0 || serialBalance32>0);

        //SOC
        self.soc = dataBytes[3 + 0x0e * 2] * 256 + dataBytes[3 + 0x0e * 2 + 1]; //SOC

        self.capacity = dataBytes[3+0x10*2]*256 + dataBytes[3+0x10*2+1];
        self.capacity = self.capacity/100.0;
        self.fullCapicity = dataBytes[3+0x11*2]*256+dataBytes[3+0x11*2+1];
        self.fullCapicity = self.fullCapicity/100.0;

        //三级保护信息
        NSInteger thirdSafeystatus = dataBytes[3+0x16*2];
        NSInteger thirdSafeystatusSecondbyte = dataBytes[3+0x16*2+1];
        //单节过压
        self.voltageSingleExceed = (thirdSafeystatusSecondbyte & 0x01) > 0 ? 1 : 0;
        //单节欠压
        self.voltageSingleLower = (thirdSafeystatusSecondbyte & 0x02) > 0 ? 1 : 0;
        //总压欠压
        self.voltageTotalLower = (thirdSafeystatusSecondbyte & 0x08) > 0 ? 1 : 0;
        //充电过流
        self.chargingExceed = (thirdSafeystatusSecondbyte & 0x10) > 0 ? 1 : 0;
        //放电过流
        self.disChargingExceed = (thirdSafeystatusSecondbyte & 0x20) > 0 ? 1 : 0;
        //充电过温
        self.chargingTemperatureExceed = (thirdSafeystatusSecondbyte & 0x40) > 0 ? 1 : 0;
        //放电过温
        self.disChargingTemperatureExceed = (thirdSafeystatusSecondbyte & 0x80) > 0 ? 1 : 0;
        //充电低温
        self.chargingTemperatureLower = (thirdSafeystatus & 0x01) > 0 ? 1 : 0;
        //放电低温
        self.disChargingTemperatureLower = (thirdSafeystatus & 0x02) > 0 ? 1 : 0;
        //压差过大
        self.voltageDifferenceExceed = (thirdSafeystatus & 0x04) > 0 ? 1 : 0;
        //放电电流
        self.disChargingCurrent = dataBytes[3+0xd*2]*256+dataBytes[3+0xd*2+1];
        //充电电流
        self.chargingCurrent = dataBytes[3+0xc*2]*256+dataBytes[3+0xc*2+1];
        //电流
        self.current = self.disChargingCurrent/10.0;
        if (self.chargingCurrent>0) {
            self.current = self.chargingCurrent/10.0;
        }
        self.isChgCurrent = self.self.disChargingCurrent==0;
//        NSLog(@"%ld-------%ld----%ld", self.isChgCurrent, self.chargingCurrent, self.disChargingCurrent);

        self.res = (thirdSafeystatus & 0x08) > 0 ? 1 : 0;//预留
        self.socLow = (thirdSafeystatus & 0x10) > 0 ? 1 : 0;//soc过低
        self.mosOver = (thirdSafeystatus & 0x20) > 0 ? 1 : 0;//mos过温
        
        environmentHighTemperature = dataBytes[3+0x0a*2]*256+dataBytes[3+0x0a*2+1];
        environmentHighTemperature = (environmentHighTemperature-400)/10; //环境最高温度
        environmenLowTemperature = dataBytes[3+0x0b*2]*256+dataBytes[3+0x0b*2+1];
        environmenLowTemperature = (environmenLowTemperature-400)/10; //环境最低温度
        NSInteger enviroment1 = dataBytes[3+0x06*2]*256+dataBytes[3+0x06*2+1];
        NSInteger enviroment2 = dataBytes[3+0x07*2]*256+dataBytes[3+0x07*2+1];
        NSInteger enviroment3 = dataBytes[3+0x08*2]*256+dataBytes[3+0x08*2+1];
        NSInteger mosT1 = dataBytes[3+0x09*2]*256+dataBytes[3+0x09*2+1];
        environmentTemperature1 = (enviroment1 - 400)/10; //环境温度1
        environmenTemperature2 = (enviroment2 - 400)/10; //环境温度2
        environmenTemperature3 = (enviroment3 - 400)/10; //环境温度3
        mosT = (mosT1 - 400)/10; //Mos温度
        [self.temperatureSensor removeAllObjects];
        [self.temperatureSensorAll removeAllObjects];
        for(int t=0; t<6; t++) {
            float temperature = dataBytes[3+t*2]*256 + dataBytes[3+t*2+1];
            [self.temperatureSensor addObject:[@((temperature-400)/10) description]];
            [self.temperatureSensorAll addObject:[@((temperature-400)/10) description]];
        }
        
        //环境温度
        [self.temperatureSensor addObject:[@(environmentTemperature1) description]];
        [self.temperatureSensorAll addObject:[@(environmentTemperature1) description]];
        [self.temperatureSensor addObject:[@(environmenTemperature2) description]];
        [self.temperatureSensorAll addObject:[@(environmenTemperature2) description]];
        [self.temperatureSensor addObject:[@(environmenTemperature3) description]];
        [self.temperatureSensorAll addObject:[@(environmenTemperature3) description]];

        float temperature = dataBytes[3+0x09*2]*256 + dataBytes[3+0x09*2+1];
        self.heatingTemp = (temperature - 400)/10;
//        if ((temperature-400)/10 != -40 && self.temperatureSensor.count==6) {
//            for (NSInteger i=0; i<self.temperatureSensor.count; i++) {
//                float temperature = [self.temperatureSensor[i] floatValue];
//                if (temperature == -40) {
//                    [self.temperatureSensor removeObjectAtIndex:i];
//                    i--;
//                }
//            }
//        }
        [self.temperatureSensor addObject:[@(self.heatingTemp) description]];
        [self.temperatureSensorAll addObject:[@(self.heatingTemp) description]];
    }
        
    if (dataBytes[2]==0x18) {
        //主机读取电池其他信息 3.4
        NSInteger secondByte = dataBytes[4];
        NSInteger threeByte = dataBytes[3];
        //预充MOS管
        self.preMOS = (secondByte & 0x02) > 0 ? 1 : 0;
        //充电MOS管
        self.chgMOS = (secondByte & 0x04) > 0 ? 1 : 0;
        //放电MOS管
        self.dsgMOS = (secondByte & 0x08) > 0 ? 1 : 0;
        //预充继电器
        self.preRelay = (secondByte & 0x10) > 0 ? 1 : 0;
        //分口充电继电器
        self.chgRelay = (secondByte & 0x20) > 0 ? 1 : 0;
        //分口放电继电器
        self.dsgRelay = (secondByte & 0x40) > 0 ? 1 : 0;
        //同口主继电器
        self.mainRelay = (secondByte & 0x80) > 0 ? 1 : 0;
        //加热继电器
        self.heatingRelay = (threeByte & 0x01) > 0 ? 1 : 0;

        self.heatMode = self.heatingRelay;
    }

    if ((dataBytes[2] == 0x60) & (reciveData.length>30)) {
        //读取序列号信息
        NSString *code = @"";
        for (NSInteger i=3; i<3+32; i++) {
            if (dataBytes[i] != 0x00 && dataBytes[i] != 0xff) {
//                NSString *c = [NSString stringWithFormat:@"%02.2hhx", dataBytes[i]];
                NSString *c = [NSString stringWithFormat:@"%c", dataBytes[i]];
                code = [code stringByAppendingString:c];
            }
        }
//        self.dcCodeLabel.text = code;
    }
    
    [self updateUI];
}

#pragma mark - UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if ([collectionView isEqual:self.typeCollect]) {
        return 9;
    }else if ([collectionView isEqual:self.voltageCollect]) {
        return self.finalserialVoltageValue.count;
    }else {
        NSInteger count = 0;
        for (NSInteger i=0; i<self.temperatureSensor.count; i++) {
            NSString *value = self.temperatureSensor[i];
            if (![value isEqualToString:@"-40"] || i == self.temperatureSensor.count-1) {
                count ++ ;
            }
        }
        return count;
    }
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([collectionView isEqual:self.typeCollect]) {
        CECategoryCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CECategoryCollectionViewCell" forIndexPath:indexPath];
        NSArray *titles = @[
            [NSString stringWithFormat:@"%@\n(V)", NSLocalizedString(@"Voltage", nil)],
            [NSString stringWithFormat:@"%@\n(A)", NSLocalizedString(@"Current", nil)],
            [NSString stringWithFormat:@"%@\n(W)", NSLocalizedString(@"Power", nil)],
            [NSString stringWithFormat:@"%@\n(V)", NSLocalizedString(@"maximum voltage", nil)],
            [NSString stringWithFormat:@"%@\n(V)", NSLocalizedString(@"minimum voltage", nil)],
            [NSString stringWithFormat:@"%@\n(V)", NSLocalizedString(@"differential pressure", nil)],
            [NSString stringWithFormat:@"%@\n(℃/℉)", NSLocalizedString(@"maximum temperature", nil)],
            [NSString stringWithFormat:@"%@\n(℃/℉)", NSLocalizedString(@"minimum temperature", nil)],
            [NSString stringWithFormat:@"%@\n(℃/℉)", NSLocalizedString(@"Mos Temperature", nil)]];
        NSArray *nums = @[[NSString stringWithFormat:@"%.2f", self.voltage],
                          [NSString stringWithFormat:@"%@%.1f", (self.isChgCurrent ? @"" : @"-"), self.current],
                          (self.current > 0 & self.voltage > 0) ? [NSString stringWithFormat:@"%.2f", self.current * self.voltage] : @"0",
                          [NSString stringWithFormat:@"%.2f", vCellMax/1000.0],
                          [NSString stringWithFormat:@"%.2f", cVellmin/1000.0],
                          [NSString stringWithFormat:@"%.3f", differentialPressure/1000.0],
                          [NSString stringWithFormat:@"%.0f/%.1f", environmentHighTemperature, environmentHighTemperature * 9 / 5.0 + 32],
                          [NSString stringWithFormat:@"%.0f/%.1f", environmenLowTemperature, environmenLowTemperature * 9 / 5.0 + 32],
                          [NSString stringWithFormat:@"%.0f/%.1f", mosT, mosT * 9 / 5.0 + 32]];
        cell.iconIV.image = [UIImage imageNamed:[NSString stringWithFormat:@"c_%ld", indexPath.item + 1]];
        cell.titleLabel.text = titles[indexPath.row];
        cell.numLabel.text = nums[indexPath.row];

        return cell;
    }else if ([collectionView isEqual:self.voltageCollect]) {
        CEVoltageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CEVoltageCollectionViewCell" forIndexPath:indexPath];
        cell.index.text = @(indexPath.item + 1).description;
        if (self.finalserialVoltageValue.count>indexPath.item) {
            cell.num.text = self.finalserialVoltageValue[indexPath.item];
        }else {
            cell.num.text = @"0";
        }

        return cell;
    }else {
        CETempCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CETempCollectionViewCell" forIndexPath:indexPath];
        NSMutableArray *arr = [NSMutableArray array];
        for (NSInteger i=0; i<self.temperatureSensor.count; i++) {
            NSString *value = self.temperatureSensor[i];
            if (![value isEqualToString:@"-40"] || i == self.temperatureSensor.count-1) {
                [arr addObject:value];
            }
        }
        cell.icon.image = [UIImage imageNamed:[NSString stringWithFormat:@"tmp_%ld", indexPath.item + 1]];
        cell.num.text = [NSString stringWithFormat:@"%@/%.1f", arr[indexPath.item], [arr[indexPath.item] floatValue] * 9 / 5.0 + 32];

        return cell;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([collectionView isEqual:self.typeCollect]) {
        return CGSizeMake((kWidth - 30)/3.0, 116);
    }else if ([collectionView isEqual:self.voltageCollect]) {
        return CGSizeMake(30, 46);
    }else {
        return CGSizeMake((kWidth - 30 - 30)/3.0, 40);
    }
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    if ([collectionView isEqual:self.typeCollect]) {
        return 3;
    }else {
        return 0;
    }
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    if ([collectionView isEqual:self.voltageCollect]) {
        return (kWidth - 240 - 30) / 7.0;
    }else if ([collectionView isEqual:self.tempCollect]) {
        return 15;
    }
    return 0;
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.protectionArray.count/3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ProtectionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ProtectionTableViewCell"];
    NSString *position = [self.protectionArray objectAtIndex:indexPath.row*3];
    NSString *positionMiddle = [self.protectionArray objectAtIndex:indexPath.row*3+1];
    NSString *positionright = [self.protectionArray objectAtIndex:indexPath.row*3+2];
    cell.level1Label.text = [self.protectValue objectAtIndex:position.integerValue];
    cell.level2Label.text = [self.protectValue objectAtIndex:positionMiddle.integerValue];
    cell.level3Label.text = [self.protectValue objectAtIndex:positionright.integerValue];

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 30;
}

#pragma PGDatePickerDelegate
- (void)datePicker:(PGDatePicker *)datePicker didSelectDate:(NSDateComponents *)dateComponents {
    NSString *year = [NSString stringWithFormat:@"%li", (long)dateComponents.year];
    NSString *month = [NSString stringWithFormat:@"%li", (long)dateComponents.month];
    NSString *day = [NSString stringWithFormat:@"%li", (long)dateComponents.day];
    if (month.length==1) month = [@"0" stringByAppendingString:month];
    if (day.length==1) day = [@"0" stringByAppendingString:day];
    self.searchDate = [NSString stringWithFormat:@"%@-%@-%@", year, month, day];
    self.mouthLabel.text = self.searchDate;
    [self getChartsHistoryData];
}

#pragma mark - sendData
- (void)queryBMS {
    //主机读取电池电压数据
    Byte write_array[8];
    write_array[0] = 0x01;
    write_array[1] = 0x03;
    write_array[2] = 0xD0;
    write_array[3] = 0x00;
    write_array[4] = 0x00;
    write_array[5] = 0x26;
    write_array[6] = 0xfc;
    write_array[7] = 0xd0;
    [[BTManager sharedBTManager] sendCommand:write_array length:8];
}

- (void)queryClock {
    //主机读取时钟及保护记录
    Byte write_array[8];
    write_array[0] = 0x01;
    write_array[1] = 0x03;
    write_array[2] = 0xD1;
    write_array[3] = 0x00;
    write_array[4] = 0x00;
    write_array[5] = 0x15;
    write_array[6] = 0xbd;
    write_array[7] = 0x39;
    [[BTManager sharedBTManager] sendCommand:write_array length:8];
}

- (void)queryBatteryTemperature {
    //3.2 主控读取电池温度电流等信息
    Byte write_array[8];
    write_array[0] = 0x01;
    write_array[1] = 0x03;
    write_array[2] = 0xD0;
    write_array[3] = 0x26;
    write_array[4] = 0x00;
    write_array[5] = 0x19;
    write_array[6] = 0x5d;
    write_array[7] = 0x0b;
    [[BTManager sharedBTManager] sendCommand:write_array length:8];
}

- (void)queryBatteryOther {
    //主机读取电池其他信息
    Byte write_array[8];
    write_array[0] = 0x01;
    write_array[1] = 0x03;
    write_array[2] = 0xD1;
    write_array[3] = 0x15;
    write_array[4] = 0x00;
    write_array[5] = 0x0c;
    write_array[6] = 0x6d;
    write_array[7] = 0x37;
    [[BTManager sharedBTManager] sendCommand:write_array length:8];
}

- (void)queryBatteryVersion {
    //主机读取电池其他信息
    Byte write_array[8];
    write_array[0] = 0x01;
    write_array[1] = 0x03;
    write_array[2] = 0xC0;
    write_array[3] = 0x02;
    write_array[4] = 0x00;
    write_array[5] = 0x30;
    write_array[6] = 0xD8;
    write_array[7] = 0x1E;
    [[BTManager sharedBTManager] sendCommand:write_array length:8];
}

#pragma mark - db
- (void)insertData:(NSString *)logName logDetail:(NSString *)logDetail {
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy/MM/dd HH:mm:ss "];
    NSDate *confromTimesp = [NSDate date];
    NSString *actiondate = [formatter stringFromDate:confromTimesp];
    NSString *sqlite = [NSString stringWithFormat:@"insert into log(logname,logdate,logdetail ) values ( '%@','%@','%@'  )" ,logName,actiondate,logDetail];
    char *error = NULL;
    int result = sqlite3_exec(db, [sqlite UTF8String], nil, nil, &error);
    if (result == SQLITE_OK) {
        NSLog(@"log insert success");
    } else {
        NSLog(@"log insert error");
    }
}

- (void)logDelete {
    NSString *sqlite = @"delete from log";
    char *error = NULL;
    int result = sqlite3_exec(db, [sqlite UTF8String], nil, nil, &error);
    if (result == SQLITE_OK) {
        NSLog(@"log delete success");
    } else {
        NSLog(@"log delete error");
    }
}

- (void)insertHistoryData:(NSDictionary *)historyDict {
    NSString *historyVoltage = historyDict[@"voltage"];
    NSString *historyCurrent = historyDict[@"current"];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss "];
    NSDate *confromTimesp = [NSDate date];
    NSString *actiondate = [formatter stringFromDate:confromTimesp];
    NSString *sqlite = [NSString stringWithFormat:@"insert into monitorData(voltage,current, logTime) values ( '%@','%@','%@'  )" ,historyVoltage, historyCurrent, actiondate];
    char *error = NULL;
    int result = sqlite3_exec(db, [sqlite UTF8String], nil, nil, &error);
    if (result == SQLITE_OK) {
        NSLog(@"insert success");
    }else {
        NSLog(@"insert error");
    }
}


- (void)getChartsHistoryData {
    NSString *date = self.searchDate;
    date = [date stringByAppendingString:@"%"];
    NSString *sqlite = [NSString stringWithFormat:@"select * from monitorData where logTime like '%@'",date];
    sqlite3_stmt *stmt = NULL;
    NSString *logText;
    int result;
    NSMutableArray *historyArray;
    historyArray=[[NSMutableArray alloc]init];
    result = sqlite3_prepare(db, sqlite.UTF8String, -1, &stmt, NULL);
    logText=@"";
    if (result == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            NSString *historyVoltage,*historyCurrent,*logdate;
            historyVoltage=[NSString stringWithCString:sqlite3_column_text(stmt, 1) encoding:NSUTF8StringEncoding];
            historyCurrent = [NSString stringWithCString:sqlite3_column_text(stmt, 2) encoding:NSUTF8StringEncoding];
            logdate=[NSString stringWithCString:sqlite3_column_text(stmt, 3) encoding:NSUTF8StringEncoding];
            NSDictionary *aDictionary;
            aDictionary=[NSDictionary dictionaryWithObjectsAndKeys:historyVoltage,@"voltage",historyCurrent,@"current",logdate,@"date", nil];
            [historyArray addObject:aDictionary];
        }
    } else {
        NSLog(@"查询失败");
    }
    sqlite3_finalize(stmt);
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.historyDataArray removeAllObjects];
        [self.historyDataArray addObjectsFromArray:historyArray];
        [self displayChart];
    });
}

- (void)initSql {
    NSString *doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *fileName=[doc stringByAppendingPathComponent:@"tennis"];
    
    const char *cfileName=fileName.UTF8String;
    
    int result = sqlite3_open(cfileName, &db);
    if (result==SQLITE_OK) {
        NSLog(@"成功打开数据库");
        const char  *sql="CREATE TABLE  log (id integer PRIMARY KEY AUTOINCREMENT,logname nvarchar(200) NOT NULL , logdate nvarchar(200) NOT NULL ,logdetail text );";
        const char  *sqlMonitor="create table if not exists monitorData(_id integer primary key autoincrement,voltage varchar (30) ,current varchar (30) ,logTime varchar(30))";
        char *err=NULL;
        result = sqlite3_exec(db, sql, NULL, NULL, &err);
        if (result==0)
        {
            NSLog(@"成功创建日志数据库");
        }
        result = sqlite3_exec(db, sqlMonitor, NULL, NULL, &err);
        if (result==0)
        {
            NSLog(@"成功创建历史数据库");
        }
    }
}

- (void)getLogData {
    NSString *sqlite = [NSString stringWithFormat:@"select * from log"];
    sqlite3_stmt *stmt = NULL;
    NSString *logText = @"";
    int result = sqlite3_prepare(db, sqlite.UTF8String, -1, &stmt, NULL);
    if (result == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            NSString *logname = [NSString stringWithCString:sqlite3_column_text(stmt, 1) encoding:NSUTF8StringEncoding];
            NSString *logdate = [NSString stringWithCString:sqlite3_column_text(stmt, 2) encoding:NSUTF8StringEncoding];
            NSString *logdetail = [NSString stringWithCString:sqlite3_column_text(stmt, 3) encoding:NSUTF8StringEncoding];
            logText = [NSString stringWithFormat:@"%@[%@] %@\n\n",logText, logdate?:@"",logdetail?:@""];
        }
    } else {
        NSLog(@"查询失败");
    }
    sqlite3_finalize(stmt);
    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"LOG_DATA_SUCCESS" object:logText];
    });
}

- (NSString*)getCurrentTimes {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];

    return currentTimeString;
}


@end

@implementation CurrentValueFormatter : NSObject

- (NSString * _Nonnull)stringForValue:(double)value entry:(ChartDataEntry * _Nonnull)entry dataSetIndex:(NSInteger)dataSetIndex viewPortHandler:(ChartViewPortHandler * _Nullable)viewPortHandler {
    return [NSString stringWithFormat:@"%.1f", entry.y*60];
}

@end

@implementation VoltageValueFormatter : NSObject

- (NSString * _Nonnull)stringForValue:(double)value entry:(ChartDataEntry * _Nonnull)entry dataSetIndex:(NSInteger)dataSetIndex viewPortHandler:(ChartViewPortHandler * _Nullable)viewPortHandler {
    return [NSString stringWithFormat:@"%.1f", entry.y*30];
}

@end
